Why does my sprite glitch when moving? [closed]
Posted
by
rphello101
on Game Development
See other posts from Game Development
or by rphello101
Published on 2012-10-03T01:48:55Z
Indexed on
2012/10/03
9:51 UTC
Read the original article
Hit count: 347
Using Slick 2D/Java, I'm using the mouse to rotate a sprite and WASD to move it (A and D are used to strafe). I finally got the directional keys and rotation to work in sync, but I'm having problems with sporadic movement. It seems that the move speed is not always set to the value I have it at. Sometimes the sprite with just shoot across the screen. Furthermore, it seems that at 0 degrees, when the left key is pressed, the sprite moves backwards, not to the left. There also seems to be quite a bit of glitching when two keys are pressed, like left and up. Anyone see anything obvious?
Here is the rotational code:
int mX = Mouse.getX();
int mY = HEIGHT - Mouse.getY();
int pX = sprite.x+sprite.image.getWidth()/2;
int pY = sprite.y+sprite.image.getHeight()/2;
double mAng;
if(mX!=pX){
mAng = Math.toDegrees(Math.atan2(mY - pY, mX - pX));
if(mAng==0 && mX<=pX)
mAng=180;
}
else{
if(mY>pY)
mAng=90;
else
mAng=270;
}
sprite.angle = mAng;
sprite.image.setRotation((float) mAng);
Movement code:
Input input = gc.getInput();
Vector2f direction = new Vector2f();
Vector2f velocity = new Vector2f();
Vector2f left;
Vector2f right;
direction.x = (float) Math.cos(Math.toRadians(sprite.angle));
direction.y = (float) Math.sin(Math.toRadians(sprite.angle));
if(direction.length()>0)
direction = direction.normalise();
left = new Vector2f(-direction.y, direction.x);
right = new Vector2f(direction.y, -direction.x);
velocity.x = (float) (direction.x * sprite.moveSpeed);
velocity.y = (float) (direction.y * sprite.moveSpeed);
if(input.isKeyDown(sprite.up)){
sprite.x += velocity.x*delta;
sprite.y += velocity.y*delta;
}if (input.isKeyDown(sprite.down)){
sprite.x -= velocity.x*delta;
sprite.y -= velocity.y*delta;
}if (input.isKeyDown(sprite.left)){
sprite.x += left.x * sprite.moveSpeed * delta;
sprite.y += left.y * sprite.moveSpeed * delta;
}if (input.isKeyDown(sprite.right)){
sprite.x += right.x * sprite.moveSpeed * delta;
sprite.y += right.y * sprite.moveSpeed * delta;
}
© Game Development or respective owner